<?php

namespace App\Admin\Actions;

use Dcat\Admin\Admin;
use Dcat\Admin\Grid\RowAction;

/**
 * 自定义URL的弹出层
 * 用法：$actions->append(mew ModelAction(admin_url('order/info')),['id'=>$actions->row->id],'订单详情',null,['800px','500px']);
 */
class ModalAction extends RowAction {
    protected string $icon='';
    protected string $titleTxt = '';
    protected string $url='';
    protected ?array $params=[];
    protected array $size=["80%","90%"];

    /**
     * @param string $url 自定义链接
     * @param array|null $params 自定义参数，未填写时默认携带当前行的所有数据
     * @param string|null $title 对话框标题
     * @param string|null $icon 对话框图标类，例如：“feather icon-file-text”
     * @param bool $fix 是否固定了最后一列
     */
    public function __construct(string $url,?array $params=null,?string $title = null,?string $icon='feather icon-link',array $size=null,bool $fix=false)
    {
        parent::__construct($title);
        $this->params=$params;
        $this->url=$url;
        if($size)$this->size=$size;
        if($icon)$this->icon=$icon;
        if($title)$this->titleTxt=$title;
        $this->title = "<span style='padding-right:10px' title='".$title."'><i class='".$icon."'></i><span class='actions-title'>".$title."</span></span>";
    }
    /**
     * 添加JS
     *
     * @return string
     */
    protected function script() {

        $size=json_encode($this->size);
        $id=unique_no();
        return <<<JS
$(".grid-modal-action").unbind('click').click(function(){
    let size=$(this).data('size').split(" ");
    if(size.length!=2)size=['80%','80%'];
    layer.open({
        type:2,
        id:"action-modal-"+$(this).data('title'),
        title:  "<div style='font-size:18px'>"+$(this).data('title')+"</div>",
        content: $(this).data('url'),
        area: size,
        queryName: '_resource_',
        items: {},
        showCloseButton: false,
    });
})

JS;
    }

    public function html() {
        //修改操作栏在横排和下拉时的样式
        $css=<<<EOF
.actions-title{
    display:none;
    padding-left:4px;
}
.dropdown-item .actions-title{
    display:inline-block!important;
}
EOF;
        Admin::style($css);
        // 这里需要添加一个class, 和上面script方法对应
        $this->setHtmlAttribute([
            'class' => 'grid-modal-action',
            'data-title'=>$this->titleTxt,
            'data-icon'=>$this->icon,
            'data-size'=>$this->size,
            'data-url'=>$this->url."?".http_build_query(empty($this->params)?$this->getRow()->toArray():$this->params)
        ]);

        return parent::html();
    }
}
